/**
 * created by haitao.yao @ Feb 22, 2011
 */
package com.googlecode.storage;

import java.nio.ByteBuffer;

/**
 * physical position for value on disk
 * 
 * @author haitao-yao
 * 
 */
public class ValuePhysicalPosition {

	/**
	 * ValuePhysicalPosition in memory
	 * <p>
	 * 4 ({@link #fileId} ) + 4 ({@link #valueSize}) + 8 ({@link #valuePosition}
	 * ) + 4 ({@link #timestamp}) = {@link #VALUE_POSITION_ENTRY_SIZE 20}
	 */
	public static final int VALUE_POSITION_ENTRY_SIZE = 20;

	/**
	 * file id
	 */
	private int fileId;

	/**
	 * value size
	 */
	private int valueSize;

	/**
	 * value position
	 */
	private long valuePosition;

	/**
	 * inner time stamp of the entry
	 */
	private int timestamp;

	public ValuePhysicalPosition() {
	}

	public static final ValuePhysicalPosition read(int position,
			ByteBuffer byteBuffer) {
		if (position + VALUE_POSITION_ENTRY_SIZE > byteBuffer.capacity()) {
			return null;
		}
		ValuePhysicalPosition result = new ValuePhysicalPosition();
		result.setFileId(byteBuffer.getInt(position))//
				.setValueSize(byteBuffer.getInt((position += 4)))//
				.setValuePosition(byteBuffer.getLong((position += 4)))//
				.setTimestamp((byteBuffer.getInt(position += 8)));
		return result;
	}

	public int getFileId() {
		return fileId;
	}

	public ValuePhysicalPosition setFileId(int fileId) {
		this.fileId = fileId;
		return this;
	}

	public int getValueSize() {
		return valueSize;
	}

	public ValuePhysicalPosition setValueSize(int valueSize) {
		this.valueSize = valueSize;
		return this;
	}

	public long getValuePosition() {
		return valuePosition;
	}

	public ValuePhysicalPosition setValuePosition(long valuePosition) {
		this.valuePosition = valuePosition;
		return this;
	}

	public int getTimestamp() {
		return timestamp;
	}

	public ValuePhysicalPosition setTimestamp(int timestamp) {
		this.timestamp = timestamp;
		return this;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + fileId;
		result = prime * result + timestamp;
		result = prime * result
				+ (int) (valuePosition ^ (valuePosition >>> 32));
		result = prime * result + valueSize;
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		ValuePhysicalPosition other = (ValuePhysicalPosition) obj;
		if (fileId != other.fileId)
			return false;
		if (timestamp != other.timestamp)
			return false;
		if (valuePosition != other.valuePosition)
			return false;
		if (valueSize != other.valueSize)
			return false;
		return true;
	}
}
